//
//  InsurancePolicyDetailViewController.m
//  CPICApp
//
//  Created by lizhiwei on 13-3-19.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "InsurancePolicyDetailViewController.h"
#import "RCAlertViewUtil.h"
#import "InsurancePolicyInfoViewController.h"
#import "SonInsuranceInfoViewController.h"
#import "CarInfoViewController.h"
#import "PaymentViewController.h"
#import "AppDelegate.h"
#import "NSString+SBJson.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "IFServiceEvaluation.h"
#import "WSqlite.h"

@interface InsurancePolicyDetailViewController ()

@end

@implementation InsurancePolicyDetailViewController
@synthesize TableIns;
@synthesize progress;
@synthesize strPolicyNo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"保单查询";
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"]) 
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"保单查询");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"保单查询");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"保单查询");
        
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }

    
    //初始化列表
    TableIns = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-44) style:UITableViewStyleGrouped];
    TableIns.dataSource = self;
    TableIns.delegate = self;
    [self.view addSubview:TableIns];
    
    ArrayIns = [[NSMutableArray alloc]initWithObjects:@"保单基本信息",@"子险信息",@"车辆信息",@"缴费信息",nil];
    
    [self setInsPolicyDetailRequest];
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Identifier=@"Identifier";
    UITableViewCell *cell=(UITableViewCell *)[TableIns dequeueReusableCellWithIdentifier:Identifier];
    if (cell==nil)
    {
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle=UITableViewCellSelectionStyleBlue;//选中后颜色没变化
        UILabel *lblInsinfo=[[UILabel alloc]initWithFrame:CGRectMake(50, 14.5, 210, 21)];
        lblInsinfo.backgroundColor=[UIColor clearColor];
        lblInsinfo.text=[ArrayIns objectAtIndex:indexPath.row];
        lblInsinfo.font = [UIFont systemFontOfSize:15.0];
        [cell addSubview:lblInsinfo];
        [lblInsinfo release];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        InsurancePolicyInfoViewController * insinfo = [[InsurancePolicyInfoViewController alloc]initView:dictpolicymain];
        [[AppDelegate app].unc pushViewController:insinfo animated:YES];
        [insinfo release];
    }
    else if(indexPath.row == 1)
    {
        SonInsuranceInfoViewController * soninsinfo = [[SonInsuranceInfoViewController alloc]initView:dictpolicycoverageList];
        [[AppDelegate app].unc pushViewController:soninsinfo animated:YES];
        [soninsinfo release];
    }
    else if(indexPath.row == 2)
    {
        CarInfoViewController * carinfo = [[CarInfoViewController alloc]initView:dictpolicyvehicleList];
        [[AppDelegate app].unc pushViewController:carinfo animated:YES];
        [carinfo release];
    }
    else if(indexPath.row == 3)
    {
        PaymentViewController * payinfo = [[PaymentViewController alloc]initView:dictpolicypaymentList];
        [[AppDelegate app].unc pushViewController:payinfo animated:YES];
        [payinfo release];
    }
    
}

-(void) ClickCallOutBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)setInsPolicyDetailRequest//向太保移动平台发送保单详情信息接口请求报文
{
    NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    WSqlite *sql =[WSqlite Instance];
    dictpolicycoverageList=[sql getPolictKindData:[dictUserInfo valueForKey:@"UserAccount"] withPolicyNo:strPolicyNo];
    dictpolicymain=[sql getPolicyMainData:strPolicyNo withUserAccount:[dictUserInfo valueForKey:@"UserAccount"]];
    dictpolicyvehicleList=[sql getPolicyCarData:strPolicyNo withUserAccount:[dictUserInfo valueForKey:@"UserAccount"]];
    NSLog(@"子险数据为--------------%@",dictpolicycoverageList);
    NSLog(@"基本信息数据为--------------%@",dictpolicymain);
    NSLog(@"车辆信息为--------------%@",dictpolicyvehicleList);
    if ([dictpolicycoverageList count]!=0 && [dictpolicymain count]!=0 && [dictpolicyvehicleList count]!=0) {
    }
    else
    {
        NSString * useraccount = [dictUserInfo valueForKey:@"UserAccount"];
        NSString *strRequestData=[NSString stringWithFormat:@"{\"policyNo\":\"%@\",\"userAccount\":\"%@\"}",strPolicyNo,useraccount];
        ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
        //设置需要POST的数据，这里提交两个数据，A=a&B=b
        [request setPostValue:@"40301" forKey:@"RequestCode"];
        [request setPostValue:strRequestData forKey:@"RequestData"];
        
        [request setDelegate:self];
        [request setDidFailSelector:@selector(ResponseFail:)];
        [request setDidFinishSelector:@selector(ResonseSuccess:)];
        [request startAsynchronous];
        
        showProgress = YES;
        if (showProgress)
        {
            progress= [[MBProgressHUD alloc]initWithView:self.view];
            [self.view addSubview:progress];
            [self.view bringSubviewToFront:progress];
            progress.labelText = @"加载中...";
            [progress show:YES];
            showProgress = NO;
        }
    }
    
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"==========responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",responseString);
    //子险信息
    dictpolicycoverageList=[dictResponse objectForKey:@"policycoverageList"];
    //保单基本信息
    dictpolicymain=[dictResponse objectForKey:@"policymain"];
    //车辆信息
    dictpolicyvehicleList=[dictResponse objectForKey:@"policyvehicleList"];
    //缴费信息
    dictpolicypaymentList=[dictResponse objectForKey:@"policypaymentList"];
   
    NSLog(@"--------------%@",dictpolicycoverageList);
    NSLog(@"--------------%@",dictpolicymain);
    NSLog(@"--------------%@",dictpolicyvehicleList);
    NSLog(@"--------------%@",dictpolicypaymentList);
    
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    WSqlite *sql =[WSqlite Instance];
    [sql insertPolicyKindData:dictpolicycoverageList withUserAccount:[dictUserInfo valueForKey:@"UserAccount"] withPolicyNo:strPolicyNo];
    [sql insertPolicyMainData:dictpolicymain withPolicyNo:strPolicyNo withUserAccouont:[dictUserInfo valueForKey:@"UserAccount"]];
    NSMutableDictionary *dictPolicyCarList=[dictpolicyvehicleList objectAtIndex:0];
    [sql insertPolicyCarData:dictPolicyCarList withPolicyNo:strPolicyNo withUserAccouont:[dictUserInfo valueForKey:@"UserAccount"]];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [TableIns release];
    [progress release];
}
-(void)dealloc
{
    [strPolicyNo release];
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
